package main

import (
	"fmt"
	"strconv"
)

func main() {
	var ht HashTable

	for i := 1; i <= 22; i++ {
		ht.Add(&Emp{No: i, Name: "张三" + strconv.Itoa(i)})
	}
	ht.Del(5)
	ht.ShowAll()

}

type Emp struct {
	No   int
	Name string
	Next *Emp
}
type EmpLink struct {
	Head *Emp
}

func (el *EmpLink) Insert(emp *Emp) {
	cur := el.Head
	var pre *Emp = nil
	if cur == nil { //说明cur为空,则插入到头节点
		el.Head = emp
		return
	}
	for {
		if cur != nil {
			if cur.No > emp.No {
				break
			}
			pre = cur
			cur = cur.Next
		} else {
			break
		}
	}
	if pre == nil { //说明插入到头节点
		emp.Next = cur
		el.Head = emp
	} else { //说明插入到非头节点
		pre.Next = emp
		emp.Next = cur
	}

}
func (el *EmpLink) Show() {
	cur := el.Head
	for cur != nil {
		fmt.Printf("[%v,%s] ", cur.No, cur.Name)
		cur = cur.Next
	}
}

type HashTable struct {
	LinkArr [7]EmpLink
}

func (this *HashTable) Add(emp *Emp) {
	index := this.HashIndex(emp.No)
	this.LinkArr[index].Insert(emp)
}
func (ht *HashTable) Del(key int) {
	index := ht.HashIndex(key)
	head := ht.LinkArr[index].Head
	var pre *Emp = nil
	for head != nil {
		if head.No == key {
			if pre == nil { //说明head就是头节点
				ht.LinkArr[index].Head = head.Next
			} else { //说明head不是头节点,则需要修改pre的next
				pre.Next = head.Next
			}
			break
		}
		pre = head       //后移
		head = head.Next //后移
	}
}

func (ht *HashTable) HashIndex(key int) int {
	return key % 7
}

func (ht *HashTable) ShowAll() {
	for i := 0; i < 7; i++ {
		fmt.Printf("i = %d: ", i)
		ht.LinkArr[i].Show()
		fmt.Println()
	}
}

func (ht *HashTable) Find(key int) *Emp {
	index := ht.HashIndex(key)
	head := ht.LinkArr[index].Head
	for head != nil {
		if head.No == key {
			return head
		}
		head = head.Next
	}
	return nil
}
